#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 * 结构体字节对齐
 *
 *	设编译选项指定的对齐值为Zp
 *	每个成员的结构体内部偏移量为 member offset
 *	成员的类型为 member type
 *	必须满足:
 *		member offset % min(sizeof(member type), Zp) == 0
 *
 *	设结构体变量自身的对齐值为Ali
 *		Ali = max(sizeof(member1 type), sizeof(member2 type)...., sizeof(memberN type))
 *
 *	必须满足:
 *		sizeof(结构体) % min(Ali, Zp) == 0
 */

struct nema
{
    char gga[8];   // 8
    char rtcm[8];  // 8
};

struct queue
{
    struct nema * queue;   // 8
    int front, rear;       // 4+4=8
    int max_size;          // 4          8+12=20, 因为对齐 ----> 24
};

struct point
{
    char * gga;
};

void main()
{
    struct nema * p = NULL;
    struct queue * qu = NULL; 
    struct point p_a, * p_b;

    printf("struct size = %ld\n", sizeof(struct nema));   // 16
    printf("struct size = %ld\n", sizeof(struct queue));  // 24
	printf("*qu size = %ld\n", sizeof(*qu));			  // 24
	printf("qu size = %ld\n", sizeof(qu));				  // 8
	printf("p_a size = %ld\n", sizeof(p_a));			  // 8
	printf("p_b size = %ld\n", sizeof(p_b));			  // 8
	
    p = (struct nema *)malloc(sizeof(struct nema));
    printf("struct size = %ld\n", sizeof(p));   // 8

    strcpy(p->gga, "abcdef");
    printf("gga = %s\n", p->gga);  // abcdef

    qu = (struct queue *) malloc (sizeof(struct queue));
    qu->queue = (struct nema *) malloc (sizeof(struct nema));
    strcpy(qu->queue->gga, "xiaozhi");  // 没有上面一行会段出错
    printf("queue->gga = %s\n", qu->queue->gga);
    free(qu->queue);
    qu->queue = NULL;

    qu->queue = p;
    printf("queue->gga = %s\n", qu->queue->gga);  // abcdef

    printf("struct point size = %ld\n", sizeof(struct point));  // 8
    
    p_a.gga = "eeef";
    printf("p_a.gga = %s\n", p_a.gga);   // eeef

    p_a.gga = "fffa";
    printf("p_a.gga = %s\n", p_a.gga);   // fffa

    //p_b->gga = "llkjl";
    //printf("p_b->gga = %s\n", p_b->gga);  // segmentation fault

    p_b = (struct point *) malloc (sizeof(struct point));
    p_b->gga = "llkjlasdfasdfasdfasdfasdfads";
    printf("p_b->gga = %s\n", p_b->gga);  // llkjlasdfasdfasdfasdfasdfads
    // strcpy(p_b->gga, "hello asm\n");      // segmentation fault.因为gga没有申请内存空间
    // printf("p_b->gga = %s\n", p_b->gga);

    p_b->gga = p_a.gga;
    printf("p_b->gga = %s\n", p_b->gga);    // fffa

    p_b->gga = (char *) malloc (sizeof(char) * 32);
    //p_b->gga = "kkkkkkkk"; // 使用这种时无需申请内存，用它上面的代码直接用，指向这串字符串
    //printf("p_b->gga = %s\n", p_b->gga);  // kkkkkkk
    strcpy(p_b->gga, "hello asm");          // 开启上面的注释代码，strcpy将会s fault, 因为先前指向的malloc申请的内存丢失.
    printf("p_b->gga = %s\n", p_b->gga);    // hello asm

    p_b->gga = p_a.gga;
    printf("p_b->gga = %s\n", p_b->gga);    // fffa

    strcpy(p_b->gga, "ac asm");             // segmentation fault. because malloc address lose 
    printf("p_b->gga = %s\n", p_b->gga);    // 

}
